package com.beiing.tianshuai.tianshuai.mine.ui;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.MyInterestContentAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.MyInterestVideoBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.interest.InterestVideoDetailActivity;
import com.beiing.tianshuai.tianshuai.mine.presenter.MyInterestContentPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.MyInterestContentViewImpl;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyInterestContentFragment extends BaseFragment implements MyInterestContentViewImpl {

    @BindView(R.id.interest_header)
    MyRefreshHeader mInterestHeader;
    @BindView(R.id.rv_interest)
    RecyclerView mRvInterest;
    @BindView(R.id.rl_empty_warning)
    RelativeLayout mRlEmptyWarning;
    @BindView(R.id.interest_footer)
    ClassicsFooter mInterestFooter;
    @BindView(R.id.srl_my_refresh_layout)
    SmartRefreshLayout mSrlMyRefreshLayout;

    /**
     * 每页请求数据的个数
     */
    private final String PAGE_SIZE = "15";

    /**
     * 当前页码
     */
    private int page = 1;

    /**
     * 当前列表的分类状态
     */
    private int status;

    /**
     * 视频列表的适配器
     */
    private MyInterestContentAdapter mAdapter;

    /**
     * presenter
     */
    private MyInterestContentPresenter mPresenter;

    /**
     * 是否是刷新状态
     */
    private boolean isRefresh;

    /**
     * 是否加载结束
     */
    private boolean isLoadFinished;

    /**
     * 网络请求重连次数
     */
    private int retryConnect;
    private int mDelPosition;

    public static MyInterestContentFragment newInstance(int type) {
        MyInterestContentFragment fragment = new MyInterestContentFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_interest_content;
    }

    @Override
    protected void init(View contentView) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            status = arguments.getInt("type");
        }
        initRecyclerView();
        initRefreshLayout();
        initListener();
        initPresenter();
    }

    /**
     * 初始化refresh layout
     * 设置下拉和上拉动作的listener
     */
    private void initRefreshLayout() {
        mSrlMyRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mSrlMyRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        // =================== 下拉刷新 =====================
        mSrlMyRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                isRefresh = true;
                isLoadFinished = false;
                mSrlMyRefreshLayout.setLoadmoreFinished(false);
                mSrlMyRefreshLayout.setEnableLoadmore(true);
                mPresenter.getMyVideoContent(UserInfoBean.getUid(mContext), PAGE_SIZE, page, status);
            }
        });
        // =================== 上拉加载 =====================
        mSrlMyRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinished) {
                    mPresenter.getMyVideoContent(UserInfoBean.getUid(mContext), PAGE_SIZE, page, status);
                } else {
                    mSrlMyRefreshLayout.setLoadmoreFinished(true);
                    mSrlMyRefreshLayout.finishLoadmore();
                }
            }
        });
    }

    private void initRecyclerView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRvInterest.setNestedScrollingEnabled(false);
        mRvInterest.setLayoutManager(linearLayoutManager);
        //绘制item间的分割线，
        mRvInterest.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 1f),
                        ContextCompat.getColor(mContext, R.color.divider_gray_light_efefef))
        );
        mAdapter = new MyInterestContentAdapter(mContext);
        mRvInterest.setAdapter(mAdapter);
    }

    private void initListener() {
        mAdapter.setListener(new MyInterestContentAdapter.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(final String id, final int i) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                        "确定删除这个视频吗？",
                        new CustomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm) {
                                    mPresenter.getDeleteResult(UserInfoBean.getUid(mContext), id);
                                    mDelPosition = i;
                                    dialog.dismiss();
                                } else {
                                    dialog.dismiss();
                                }
                            }
                        }).setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        });

        mAdapter.setOnItemClickListener(new MyInterestContentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String id, int position, String typeName) {
                Intent intent = new Intent(mContext, InterestVideoDetailActivity.class);
                intent.putExtra("vid", id);
                intent.putExtra("typeName", typeName);
                startActivity(intent);
            }
        });
    }

    private void initPresenter() {
        mPresenter = new MyInterestContentPresenter(this);
        mPresenter.getMyVideoContent(UserInfoBean.getUid(mContext), PAGE_SIZE, page, status);
    }

    @Override
    public void getMyInterestContentSuccess(MyInterestVideoBean bean) {
        retryConnect = 0;
        List<MyInterestVideoBean.DataBean.VideoBean> video = bean.getData().getVideo();

        int size = video.size();
        if (size == 0) {
            isLoadFinished = true;
            mSrlMyRefreshLayout.setLoadmoreFinished(true);
        } else if (size == Integer.valueOf(PAGE_SIZE)) {
            if (isRefresh) {
                mAdapter.updateData(video);
                isRefresh = false;
            } else {
                mAdapter.appendData(video);
            }
        } else {
            if (isRefresh) {
                mAdapter.updateData(video);
                isRefresh = false;
            } else {
                mAdapter.appendData(video);
            }
            mSrlMyRefreshLayout.setLoadmoreFinished(true);
        }


        // 加载更多结束页码增加 结束加载
        if (mSrlMyRefreshLayout.isLoading()) {
            page++;
            mSrlMyRefreshLayout.finishLoadmore();
        }
        // 刷新结束 重置页码 结束刷新
        if (mSrlMyRefreshLayout.isRefreshing()) {
            page = 1;
            mSrlMyRefreshLayout.finishRefresh();
        }
    }

    @Override
    public void getMyInterestContentError(Throwable throwable) {
        if ((retryConnect < 5)) {
            retryConnect ++;
            mPresenter.getMyVideoContent(UserInfoBean.getUid(mContext), PAGE_SIZE, page, status);
        } else {
            retryConnect = 0;
            showShortText("请求失败");
        }
    }

    @Override
    public void onDeleteSuccess(CodeBean bean) {
        mAdapter.removeData(mDelPosition);
    }

    @Override
    public void onDeleteError(Throwable throwable) {
        LogUtils.e(throwable.getMessage(), "error");
    }
}
